<template>
  <div class="warp">
    <div class="accumulate">
      <div class="tab">
        <p
          v-for="(item, index) in tab"
          :key="index"
          :class="{ active: tabIndex == index }"
          @click="changeTabIndex(index)"
        >
          {{ item }}
        </p>
      </div>

      <div class="echartsBox">
        <div id="collEcharts" class="echarts" />
        <div class="select" @click="showPicker = true">
          {{ pickerText }}年<van-icon name="arrow-down" />
        </div>
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            v-model="pickerText"
            show-toolbar
            :columns="columns"
            @confirm="onConfirm"
            @cancel="showPicker = false"
          />
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script>
import { http_farmland } from '@/api';
export default {
  data() {
    return {
      tab: ['积温', '积雨'],
      tabIndex: 0,

      showPicker: false,
      pickerText: '',
      columns: [],

      prcpHistory: [], // 积雨30年平均
      prcpLast: [], // 积雨去年
      prcpNow: [], // 积雨今年
      tempHistory: [], // 积温30年平均
      tempLast: [], // 积温去年
      tempNow: [] // 积温今年
    };
  },
  computed: {
    xAxis() {
      return this.$route.query.xaxis;
    },
    yAxis() {
      return this.$route.query.yaxis;
    }
  },
  mounted() {
    const year = new Date().getFullYear();
    this.pickerText = year.toString();
    this.getYear();

    this.getAccWeatherFn();

    const timeArr = this.getDateBetween(
      `${this.pickerText}-01-01`,
      `${this.pickerText}-12-31`
    );
    this.dayList = timeArr;
  },
  methods: {
    // 获取积温积雨
    async getAccWeatherFn() {
      const result = await http_farmland.accumulate({
        xAxis: this.xAxis,
        yAxis: this.yAxis,
        year: this.pickerText
      });
      if (result.code == 200) {
        const prcpHistory = result.data.prcpHistory;
        for (var i = 0; i < prcpHistory.length; i++) {
          prcpHistory[i] = Number(prcpHistory[i]).toFixed(2);
        }
        this.prcpHistory = prcpHistory;

        const prcpNow = result.data.prcpNow;
        for (var i = 0; i < prcpNow.length; i++) {
          prcpNow[i] = Number(prcpNow[i]).toFixed(2);
        }
        this.prcpNow = prcpNow;

        const tempHistory = result.data.tempHistory;
        for (var i = 0; i < tempHistory.length; i++) {
          tempHistory[i] = Number(tempHistory[i]).toFixed(2);
        }
        this.tempHistory = tempHistory;

        const tempNow = result.data.tempNow;
        for (var i = 0; i < tempNow.length; i++) {
          tempNow[i] = Number(tempNow[i]).toFixed(2);
        }
        this.tempNow = tempNow;

        this.getAccWeatherLastFn();
      }
    },
    // 获取积温积雨--去年
    async getAccWeatherLastFn() {
      const result = await http_farmland.accumulate({
        xAxis: this.xAxis,
        yAxis: this.yAxis,
        year: this.pickerText - 1
      });
      if (result.code == 200) {
        const prcpNow = result.data.prcpNow;
        for (var i = 0; i < prcpNow.length; i++) {
          prcpNow[i] = Number(prcpNow[i]).toFixed(2);
        }
        this.prcpLast = prcpNow;

        const tempNow = result.data.tempNow;
        for (var i = 0; i < tempNow.length; i++) {
          tempNow[i] = Number(tempNow[i]).toFixed(2);
        }
        this.tempLast = tempNow;

        this.drawChart();
      }
    },
    getYear() {
      // 获取年份，当前年前后5年
      var y = new Date().getFullYear();
      const years = [];
      for (var i = 0; i <= 5; i++) {
        if (i < 5) {
          years.unshift(y - i);
        }
      }
      this.columns = years;
    },
    getDateBetween(start, end) {
      var result = [];
      // 使用传入参数的时间
      var startTime = new Date(start);
      var endTime = new Date(end);
      while (endTime - startTime >= 0) {
        let month = startTime.getMonth();
        month = month < 9 ? '0' + (month + 1) : month + 1;
        const day =
          startTime.getDate().toString().length == 1
            ? '0' + startTime.getDate()
            : startTime.getDate();
        // 加入数组
        result.push(month + '-' + day);
        // 更新日期
        startTime.setDate(startTime.getDate() + 1);
      }
      return result;
    },
    changeTabIndex(index) {
      this.tabIndex = index;
      this.drawChart();
    },
    onConfirm(value) {
      this.pickerText = value;
      this.showPicker = false;
      this.getAccWeatherFn();
    },
    goBack() {
      this.$router.go(-1);
    },
    drawChart() {
      const that = this;
      const colorList = ['#1777FD', '#32C45E', '#FFA71C'];
      const myChart = that.$echarts.init(document.getElementById('collEcharts'));
      const timeList = that.dayList;
      let thirtyList = [];
      let lastList = [];
      let thisList = [];
      let text = '';
      let com = '';
      if (that.tabIndex == 0) {
        thirtyList = that.tempHistory;
        lastList = that.tempLast;
        thisList = that.tempNow;
        text = '积温';
        com = '℃';
      } else {
        thirtyList = that.prcpHistory;
        lastList = that.prcpLast;
        thisList = that.prcpNow;
        text = '积雨';
        com = 'mm';
      }

      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#ffffff',
          borderRadius: 10,
          extraCssText: 'box-shadow: 0px 2px 5px 1px rgba(0,0,0,0.07);',
          formatter: function(params) {
            console.log(params);
            if (params.length == 3) {
              return `<div class='tip' style="color: #D45B0B;">
                <div class='tit'>${that.pickerText}.${params[0].axisValue}</div>
                <div class='item'>
                  <div class='label'>${params[0].seriesName}${text}</div>
                  <div class='input'>${params[0].value}${com}</div>
                </div>
                <div class='item'>
                  <div class='label'>${params[1].seriesName}${text}</div>
                  <div class='input'>${params[1].value}${com}</div>
                </div>
                <div class='item'>
                  <div class='label'>${params[2].seriesName}${text}</div>
                  <div class='input'>${params[2].value}${com}</div>
                </div>
              </div>`;
            } else if (params.length == 2) {
              return `<div class='tip' style="color: #D45B0B;">
                <div class='tit'>${that.pickerText}.${params[0].axisValue}</div>
                <div class='item'>
                  <div class='label'>${params[0].seriesName}${text}</div>
                  <div class='input'>${params[0].value}${com}</div>
                </div>
                <div class='item'>
                  <div class='label'>${params[1].seriesName}${text}</div>
                  <div class='input'>${params[1].value}${com}</div>
                </div>
                <div class='item'>
                  <div class='label'>今年${text}</div>
                  <div class='input'>0${com}</div>
                </div>
              </div>`;
            }
          }
        },
        dataZoom: [
          {
            // 控制图表左右滑动
            width: '15',
            type: 'slider',
            show: false, // flase直接隐藏图形
            xAxisIndex: [0],
            left: 33, // 滚动条靠左侧的百分比
            bottom: 40,
            height: 20, // 组件高度
            start: 0, // 滚动条的起始位置
            showDataShadow: false, // 是否显示数据阴影
            showDetail: false, // 是否显示想洗数值信息
            end: 50 // 滚动条的截止位置（按比例分割你的柱状图x轴长度）
          },
          {
            type: 'inside',
            show: true,
            xAxisIndex: [0],
            start: 0, // 滚动条的起始位置
            end: 0.25 // 滚动条的截止位置（按比例分割你的柱状图x轴长度）
          }
        ],
        grid: {
          x: 60,
          x2: 50,
          y: 50,
          y2: 40
        },
        color: colorList,
        legend: {
          x: 'right',
          y: 'top',
          padding: [20, 50, 0, 0],
          data: ['30年平均', '去年', '今年']
        },
        xAxis: {
          type: 'category',
          data: timeList,
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              width: 1,
              color: '#909099'
            }
          },
          axisLabel: {
            color: '#504F4F'
          }
        },
        yAxis: {
          type: 'value',
          name: `${text}(${com})`,
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              width: 1,
              color: '#909099'
            }
          },
          axisLabel: {
            color: '#504F4F',
            formatter: function(value) {
              return value;
            }
          }
        },
        series: [
          {
            name: '30年平均',
            type: 'line',
            smooth: true,
            showSymbol: false,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dashed' // 'dotted'点 'dashed'虚线 'solid'实线
                }
              }
            },
            data: thirtyList
          },
          {
            name: '去年',
            type: 'line',
            smooth: true,
            showSymbol: false,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dashed' // 'dotted'点 'dashed'虚线 'solid'实线
                }
              }
            },
            data: lastList
          },
          {
            name: '今年',
            type: 'line',
            smooth: true,
            showSymbol: false,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dashed' // 'dotted'点 'dashed'虚线 'solid'实线
                }
              }
            },
            data: thisList
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    }
  }
};
</script>

<style lang="scss" scoped>
.warp {
  width: 100%;
}
.accumulate {
  display: flex;
  flex-direction: column;
  .tab {
    padding: 9px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 400;
    color: #3c3c3c;
    position: relative;
    p {
      margin: 0 58px;
    }
    p.active {
      font-weight: bold;
      color: #ffa10b;
      position: relative;
    }
    p.active::after {
      content: "";
      position: absolute;
      width: 29px;
      height: 3px;
      background: #ffa10b;
      border-radius: 1px;
      left: 50%;
      transform: translateX(-50%);
      bottom: -4px;
    }
    .van-icon {
      position: absolute;
      left: 19px;
      top: 19px;
    }
  }

  ::v-deep .tip {
    padding: 0 16px 7px;
    .tit {
      height: 43px;
      display: flex;
      align-items: center;
      font-size: 14px;
      font-weight: 400;
      color: #504f4f;
      border-bottom: 1px solid #f2f2f3;
      margin-bottom: 12px;
    }
    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 4px 0;
      .label {
        font-size: 12px;
        font-weight: 400;
        color: #8f8f8f;
        margin-right: 18px;
      }
      .input {
        font-size: 12px;
        font-weight: 400;
        color: #504f4f;
      }
    }
  }

  .echartsBox {
    width: 100%;
    flex: 1;
    position: relative;
    .echarts {
      height: 300px;
      width: 100%;
    }
    .select {
      position: absolute;
      top: 17px;
      left: 120px;
      width: 68px;
      height: 21px;
      border-radius: 1px;
      border: 1px solid #32c45e;
      font-size: 12px;
      font-weight: 400;
      color: #32c45e;
      padding: 0 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}
</style>
